import {
	defineStore
} from 'pinia';
import {
	useUserStore
} from "@/stores/user.js"
import {
	SERVER_URL
} from "@/config/index.js"

export const useOrderStore = defineStore('order', {
	state: () => {
		return {
			products: [],
			shoppingAddress: null,
			presale_delivery_date: null,
			presale: false,
			presale_delivery_date: null
		};
	},
	actions: {
		settlement(e) {
			const userStore = useUserStore()

			this.products = e.products
			this.presale = e.presale ? true : false
			this.presale_delivery_date = e.presale_delivery_date ?? null

			if (this.shoppingAddress === null) {
				uni.request({
					url: SERVER_URL + '/customer/shipping-address/default',
					method: "GET",
					header: {
						"content-type": "application/json",
						"authorization": userStore.token
					},
					success: (res) => {
						if (res.statusCode === 200) {
							if (res.data) this.shoppingAddress = res.data
						}
					}
				});
			}
			uni.navigateTo({
				url: "/pages/order/settlement"
			})
		},
		setAddress(e) {
			this.shoppingAddress = e
		}
	},
	persist: {
		// 调整为兼容多端的API
		storage: {
			setItem(key, value) {
				uni.setStorageSync(key, value)
			},
			getItem(key) {
				return uni.getStorageSync(key)
			},
		},
	}
});